package gw.com.android.ui.onlive;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.util.List;
import java.util.Locale;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.presenter.http.DiscussRequest;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.MyConcernRequest;
import gw.com.android.ui.me_concern.AnalystData;
import gw.com.android.ui.views.ImageWatcher;
import gw.com.android.utils.CacheUtils;
import gw.com.android.utils.NetUtil;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.interfaces.ReqCallBack;
import www.com.library.view.XRecyclerView;

/**
 * 圈子，base fragment，抽象类，不允许直接使用
 */
public abstract class QuanziListFragment extends Fragment {

    //现在把圈子的逻辑拿过来，
    private XRecyclerView mListView;
    private LinearLayout ll_error, ll_no_content;
    private TextView tv_no_content;

    private DiscussAdapter discussAdapter;
    private String[] followedAnalyst = new String[1];
    private DiscussRequest request;
    private ImageWatcher imageWatcher;
    private List<DiscussData> mData;//内存中，存一份数据，因为有可能用来刷新adapter的部分视图

    // 封装方法，获取当前所有分析师
    private MyConcernRequest myConcernRequest;
    protected int currentTradeType = DiscussRequest.TRADE_TYPE_ANALYST;//当前帖子类型,值，参照 DiscussRequest 的final常量

    public void setImageWatcher(ImageWatcher temp) {
        this.imageWatcher = temp;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CacheUtils.writeFile(CacheUtils.CACHE_FIRST_COMING_2_2, "true");
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_quanzi, container, false);
        initView(root);
        return root;
    }

    @Override
    public void onResume() {//经过实战检测，这个Resume只会在fragment所在的activity重新回到视线内的时候，才会执行
        super.onResume();
        refreshFollowedAnalystForPartialRefresh(true);
        //还要同步所有的点赞数目和转发数目
    }

    private boolean ifInitViewFinished = false;

    protected void initView(View root) {
        // 初始化RecyclerView
        tips = (TextView) root.findViewById(R.id.tv_tips);
        ll_error = (LinearLayout) root.findViewById(R.id.ll_error);
        ll_no_content = (LinearLayout) root.findViewById(R.id.ll_no_content);
        ll_no_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                loadData(currentTradeType);
                refreshFollowedAnalyst();
            }
        });
        tv_no_content = (TextView) root.findViewById(R.id.tv_no_content);
        TextView tv_refresh = (TextView) root.findViewById(R.id.tv_refresh);

        tv_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListView.setRefreshing(true);
            }
        });

        mListView = (XRecyclerView) root.findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager layoutManager = new FastScrollLinearLayoutManager(getContext());
        mListView.setLayoutManager(layoutManager);
        request = new DiscussRequest();

        mListView.resetTimeZone();
        mListView.setAdapter(new EmptyAdapter());// 初始状态，给list加载占位的布局
        mListView.hideFooter();
        initDataAdapter();//初始化真实数据adapter

        mListView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
//                loadData(currentTradeType);
                refreshFollowedAnalyst();
            }

            @Override
            public void onLoadMore() {
//                nextPage();//这个nextPage，不再是下拉到底的时候才去执行，而是，滑到当前list 的item总数的倒数第二项的时候执行
            }
        });
        mListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int last = linearLayoutManager.findLastVisibleItemPosition();//这个计数是从1开始 ，不是0，

                //把它和倒数
                int total = discussAdapter.getItemCount();
                if (last >= total - 3) {//当最后一项是 总数的倒数第三项的时候，开始加载下一页
                    nextPage();
                }
                Log.d("QuanziListLisCallback", last + "/" + total);
            }
        });
        initListViewScrollCallback();
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {//在没有登录的情况下
            fetchLocalData();//那么，直接获取本地数据即可
        } else
            refreshFollowedAnalyst();//由于这里要设置分析师的关注状态，所以必须先取出我关注的分析师，做个标记。不然，在上下滑动的时候，关注的状态会混乱
        ifInitViewFinished = true;
    }

    private void refreshFollowedAnalyst() {
        // 进入这个页面之前，先取出我关注的分析师
        if (myConcernRequest == null) {
            myConcernRequest = new MyConcernRequest();
        }
        //如果是登录了，那就先获取当前用户关注的分析师；因为这里涉及到RecyclerView的item复用，必须先把关注情况记录下来，防止在滑动的时候造成 关注状态混乱
        myConcernRequest.getFollowedAnalystList(GTConfig.instance().mCurName, new HttpCallback<List<AnalystData>>() {
            @Override
            public void onSuccess(List<AnalystData> result) {
                if (result == null)
                    followedAnalyst = new String[]{};
                else {
                    followedAnalyst = new String[result.size()];
                    int i = 0;
                    for (AnalystData data : result) {
                        followedAnalyst[i] = data.userNo;
                        i++;
                    }
                }
                loadData(currentTradeType);
            }

            @Override
            public void onFailure(Exception e) {
                Log.d("QuanziListTag1", "侦测到请求异常，可能是网络原因，可能是后台原因: " + e == null ? "exception是空" : e.getLocalizedMessage());
                mListView.refreshComplete();
                onFailed();
            }
        });
    }

    private void initDataAdapter() {
        discussAdapter = new DiscussAdapter(currentTradeType, getActivity());
        discussAdapter.setWatcher(imageWatcher);
    }

    private boolean ifDataAdapter = false;// 用一个变量标记，当前是否使用了数据adapter

    private void setDataAdapter() {
        if (!ifDataAdapter) {// 如果当前使用的不是数据adapter，那么就进行设置
            mListView.setAdapter(discussAdapter);
            mListView.hideFooter();
            ifDataAdapter = true;
        }
    }

    private void fetchLocalData() {
        final List<DiscussData> list = request.fetchLocal(currentTradeType, null);
        if (list != null && !list.isEmpty()) {
            mData = list;
            refreshUi(list, true);
        } else {
            mListView.setRefreshing(true);//原来这个代码，会直接触发onRefresh，从而调用loadData.
        }
    }

    /**
     * 下拉刷新以及首次加载
     */
    private void loadData(int tradeType) {
        currentTradeType = tradeType;
        showListView();
        request.getList(new ReqCallBack<List<DiscussData>>() {
            @Override
            public void onReqSuccess(final List<DiscussData> result) {
                Log.d("resultSizeX", "" + (result == null ? "0" : result.size()));
                setDataAdapter();
                if (result != null && result.size() != 0 && currentTradeType == DiscussRequest.TRADE_TYPE_ALL) {//如果是查询的全部帖子，那就在有新帖子的时候谈tip提示
                    showTips(result);
                }
                mListView.refreshComplete();
                mData = result;
                refreshUi(result, true);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.d("QuanziListTag2", "侦测到请求异常，可能是网络原因，可能是后台原因: " + errorMsg);
                mListView.refreshComplete();
                onFailed();
            }
        }, tradeType, false, GTConfig.instance().mCurName);
    }

    private boolean ifNextPageRunning = false;

    /**
     * 加载更多
     */
    private void nextPage() {
        if (ifNextPageRunning) return;
        Log.d("QuanziListLisCallback", "加载下一页");
        ifNextPageRunning = true;
        request.nextPage(new ReqCallBack<List<DiscussData>>() {
            @Override
            public void onReqSuccess(List<DiscussData> list) {
                ifNextPageRunning = false;
                loadMoreRefreshUi(list);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                mListView.loadMoreComplete();
                ifNextPageRunning = false;
                onFailed();
            }
        });
    }

    /**
     * 当请求失败时
     */
    private void onFailed() {
        // 判断当前网络是否正常，如果正常，就显示 error布局，否则就提示网络异常tip
        if (NetUtil.isNetworkAvailable(getContext()))//如果有网络,然而还是失败，就显示异常布局
            showNetErrorLayout();
        else//如果没网络，就弹窗
            new ToastPopWindow(getContext(), getContext().getString(R.string.no_network_error2)).show();
    }

    private void refreshUi(List<DiscussData> list, boolean ifHideConcernButton) {
        if (list != null && !list.isEmpty()) {
            setDataAdapter();
            discussAdapter.setData(list, followedAnalyst, ifHideConcernButton, false);//这是整体刷新
        } else {
            showNoContent();
        }

        int itemCount = discussAdapter.getItemCount();
        if (itemCount <= 0) {
            mListView.setNoMore(false);
            mListView.hideFooter();
        } else {
            mListView.setNoMore(!request.hasNextPage());
        }
    }


    /**
     * 空adapter布局，用于占位
     */
    private class EmptyAdapter extends RecyclerView.Adapter<EmptyAdapter.EmptyHolder> {

        class EmptyHolder extends RecyclerView.ViewHolder {
            EmptyHolder(View itemView) {
                super(itemView);
            }
        }

        @Override
        public EmptyAdapter.EmptyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = View.inflate(getContext(), R.layout.item_discuss_empty, null);
            return new EmptyAdapter.EmptyHolder(itemView);
        }

        @Override
        public void onBindViewHolder(EmptyAdapter.EmptyHolder holder, int position) {
        }

        @Override
        public int getItemCount() {
            return 2;
        }
    }


    private TextView tips;
    private Runnable animTask;

    private void showTips(List<DiscussData> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        List<String> ids = discussAdapter.getIds();
        if (ids == null || ids.isEmpty()) {
            showTips(list.size());
            return;
        }
        int count = 0;
        for (DiscussData data : list) {
            if (!ids.contains(data.id)) {
                count++;
            }
        }
        if (count > 0) {
            showTips(count);
        }
    }

    // 当前更新了%条帖子
    private void showTips(int count) {
        String text = String.format(Locale.getDefault(), getString(R.string.home_trade_news_update_count), count);
        tips.setText(text);
        tips.setVisibility(View.VISIBLE);
        tips.clearAnimation();
        if (animTask != null) {
            AppMain.getApp().getHandler().removeCallbacks(animTask);
            animTask = null;
        }
        TranslateAnimation tranAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
        AlphaAnimation alphaAnim = new AlphaAnimation(0, 1);
        AnimationSet animSet = new AnimationSet(true);
        animSet.addAnimation(tranAnim);
        animSet.addAnimation(alphaAnim);
        animSet.setDuration(200);
        animSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                hideTipsDelay();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        tips.startAnimation(animSet);
    }

    private void hideTipsDelay() {
        animTask = new Runnable() {
            @Override
            public void run() {
                hideTips();
            }
        };
        AppMain.getApp().getHandler().postDelayed(animTask, 800);
    }

    private void hideTips() {
        TranslateAnimation tranAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1);
        AlphaAnimation alphaAnim = new AlphaAnimation(1, 0);
        AnimationSet animSet = new AnimationSet(true);
        animSet.addAnimation(tranAnim);
        animSet.addAnimation(alphaAnim);
        animSet.setDuration(200);
        animSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                tips.setVisibility(View.GONE);
                animTask = null;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        animSet.setFillAfter(true);
        tips.startAnimation(animSet);
    }


    private void showNetErrorLayout() {
        ll_no_content.setVisibility(View.GONE);
        ll_error.setVisibility(View.VISIBLE);
        mListView.setVisibility(View.GONE);
    }

    private void showListView() {
        ll_no_content.setVisibility(View.GONE);
        ll_error.setVisibility(View.GONE);
        mListView.setVisibility(View.VISIBLE);
    }

    private void showNoContent() {
        ll_no_content.setVisibility(View.VISIBLE);
        ll_error.setVisibility(View.GONE);
        mListView.setVisibility(View.GONE);

        String noContentTipText;
        switch (currentTradeType) {
            case DiscussRequest.TRADE_TYPE_ANALYST:
                noContentTipText = "暂无分析师帖";
                break;
            case DiscussRequest.TRADE_TYPE_BEST:
                noContentTipText = "暂无精华帖";
                break;
            case DiscussRequest.TRADE_TYPE_GUEST:
                noContentTipText = "暂无晒单";
                break;
            case DiscussRequest.TRADE_TYPE_ALL:
            default:
                noContentTipText = "暂无动态";
                break;
        }
        tv_no_content.setText(noContentTipText);
    }

    public void refreshListData() {
        try {
            // 看看initView是不是完成了
            if (ifInitViewFinished) {
                mListView.scrollToPosition(0);
                mListView.setRefreshing(true);
            }
        } catch (Exception e) {
        }
    }

    public void scrollListToTop() {
        if (mListView != null) {
            mListView.smoothScrollToPosition(0);
        }
    }

    private void loadMoreRefreshUi(List<DiscussData> list) {
        mListView.loadMoreComplete();
        mListView.setNoMore(!request.hasNextPage());
        discussAdapter.addData(list);
    }

    // 给listView增加一个回调
    public interface OnScrollCallback {
        void onScroll(int p);
    }

    private OnScrollCallback onScrollCallback;

    public void setOnScrollCallback(OnScrollCallback onScrollCallback) {
        this.onScrollCallback = onScrollCallback;
    }

    private void initListViewScrollCallback() {
        mListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int p = linearLayoutManager.findFirstVisibleItemPosition();//第一个(可能是部分)可见的item的位置
                Log.d("ListViewScrollCallback", p + "");
                onScrollCallback.onScroll(p);
            }
        });
    }

    //新增一个方法,用于同步所有的分析师关注按钮状态
    public void refreshFollowedAnalystForPartialRefresh(final boolean ifHideConcernButton) {
        if (mData == null) return;
        // 进入这个页面之前，先取出我关注的分析师
        if (myConcernRequest == null) {
            myConcernRequest = new MyConcernRequest();
        }
        //如果是登录了，那就先获取当前用户关注的分析师；因为这里涉及到RecyclerView的item复用，必须先把关注情况记录下来，防止在滑动的时候造成 关注状态混乱
        myConcernRequest.getFollowedAnalystList(GTConfig.instance().mCurName, new HttpCallback<List<AnalystData>>() {
            @Override
            public void onSuccess(List<AnalystData> result) {
                if (result == null)
                    followedAnalyst = new String[]{};
                else {
                    followedAnalyst = new String[result.size()];
                    int i = 0;
                    for (AnalystData data : result) {
                        followedAnalyst[i] = data.userNo;
                        i++;
                    }
                }
                refreshUi(mData, ifHideConcernButton);
            }

            @Override
            public void onFailure(Exception e) {
                Log.d("QuanziListTag1", "侦测到请求异常，可能是网络原因，可能是后台原因: " + e == null ? "exception是空" : e.getLocalizedMessage());
                mListView.refreshComplete();
                onFailed();
            }
        });
    }

}
